package top.dreamcenter.rss.rsssolverweb.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import top.dreamcenter.rss.rsssolverprotocal.SpiderTemplate;
import top.dreamcenter.rss.rsssolverweb.util.RedisHelper;
import top.dreamcenter.rss.rsssolverweb.util.ScheduleHelper;
import top.dreamcenter.rss.rsssolverweb.util.SpiderHelper;
import top.dreamcenter.rss.rsssolverweb.util.SpiderHelperFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class BeanRegister {


    /**
     * 获取容器中注册的所有插件，并且注册为爬虫工具
     * @param context
     * @param spiderHelperFactory
     * @return
     */
    @Bean
    public Map<String, SpiderHelper> spiders(
            ApplicationContext context,
            SpiderHelperFactory spiderHelperFactory,
            ScheduleHelper scheduleHelper,
            RedisHelper redisHelper) {
        Map<String, SpiderTemplate> beansOfType = context.getBeansOfType(SpiderTemplate.class);
        Map<String, SpiderHelper> helperMap = new HashMap<>();
        beansOfType.forEach((k, spider) -> {
            SpiderHelper spiderHelper = spiderHelperFactory.creator(spider);
            // 从redis装载初始化数据 plugin-{key|config} [<k,v>,]
            Map<String, String> keys = redisHelper.getHashResults(spiderHelper.getRoute() + "-key");
            Map<String, String> configs = redisHelper.getHashResults(spiderHelper.getRoute() + "-config");
            keys.forEach(spiderHelper::addKey);
            configs.forEach(spiderHelper::addConfig);

            // 注册到自动任务
            scheduleHelper.registerSchedule(spiderHelper);
            // 放到容器中
            helperMap.put(k, spiderHelper);
        });
        return helperMap;
    }


    /**
     * 自动任务线程池
     * @return
     */
    @Bean
    public ThreadPoolTaskScheduler syncScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(6);
        scheduler.setThreadGroupName("pluginTasks");
        scheduler.setThreadNamePrefix("syncThread-");
        scheduler.initialize();
        return scheduler;
    }

}
